package com.yang.lesson02;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//简易计算器
public class TestCalc {
    //执行所用main方法
    public static void main(String[] args) {
        new Calculator().loadFrame();
    }
}

//计算器类
class Calculator extends Frame{
    TextField num1,num2,num3;

    public void loadFrame(){
        //窗口设置
        pack();
        setVisible(true);

        //窗口布局
        setLayout(new FlowLayout());

        //三个文本框
        num1 = new TextField(10);//字符数
        num2 = new TextField(10);
        num3 = new TextField(20);

        //一个标签
        Label label = new Label("+");

        //一个按钮
        Button button = new Button("=");
        //对按钮进行监听
        button.addActionListener(new MyCalculatorListener());

        //组合窗口
        add(num1);
        add(label);
        add(num2);
        add(button);
        add(num3);

        //关闭方法
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }
    //监听器类
    //内部类最大的好处，可以畅通无阻的访问外部类
    private class MyCalculatorListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            //获取加数与被加数
            int n1 = Integer.parseInt(num1.getText());
            int n2 = Integer.parseInt(num2.getText());
            //进行运算,并将值放入第三个框
            num3.setText(""+(n1+n2));

            //清空前两个框
            num1.setText("");
            num2.setText("");
        }
    }

}

